package org.jsola.hr.web;

import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.AttendanceDataTempAddDTO;
import org.jsola.hr.dto.AttendanceDataTempUpdateDTO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.query.AttendanceDataTempQuery;
import org.jsola.hr.service.IAttendanceDataTempService;
import org.jsola.hr.vo.AttendanceDataAllAndErrorVO;
import org.jsola.hr.vo.AttendanceDataTempListVO;
import org.jsola.hr.vo.AttendanceDataTempVO;
import org.jsola.hr.vo.ParseAttendanceDataTempExcelVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import javax.validation.Valid;


/**
 * 临时考勤数据
 *
 * @author zhr
 */
@RestController("hrAttendanceDataTempController")
@RequestMapping(HrConstants.API_PATH + "/v1/attendanceDataTemps")
public class AttendanceDataTempController implements IAttendanceDataTempControllerAPI {

    @Autowired
    private IAttendanceDataTempService attendanceDataTempService;

    @Override
    @GetMapping("/importMonthSallary")
    public Result<Integer> importMonthSallary(AttendanceDataTempQuery attendanceDataTempQuery) {
        TokenUser tokenUser = UserContext.getUser();
        return Result.success(
                attendanceDataTempService.importMonthSallary(attendanceDataTempQuery,tokenUser)
        );
    }

    @Override
    @PutMapping("/importMonthSalary")
    public Result<Integer> importMonthSalary(@RequestBody AttendanceDataTempQuery attendanceDataTempQuery) {
        TokenUser tokenUser = UserContext.getUser();
        return Result.success(
                attendanceDataTempService.importMonthSalary(attendanceDataTempQuery,tokenUser)
        );
    }

    @Override
    @GetMapping("/errorDataExcelByRecordId/{recordId}")
    public ResponseEntity<Resource> errorDataExcelByRecordId(@PathVariable String recordId) {
        TokenUser tokenUser = UserContext.getUser();
        // 模板文件
        AttendanceDataTempVO attendanceDataTempVO = attendanceDataTempService.errorDataExcelByRecordId(recordId, tokenUser);
        InputStream is = attendanceDataTempVO.getIs();
        String name = attendanceDataTempVO.getFileName();
        ParamException.notNull(is, "模板生成失败");

        // 编码文件名，防止乱码
        String filenames = new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE,"application/vnd.ms-excel")
                .body(new InputStreamResource(is));
    }

    @Override
    @GetMapping("/getErrorDataExcel/{recordId}")
    public ResponseEntity<Resource> getErrorDataExcel(@PathVariable String recordId) {
        TokenUser tokenUser = UserContext.getUser();
        // 模板文件
        AttendanceDataTempVO attendanceDataTempVO = attendanceDataTempService.getErrorDataExcel(recordId, tokenUser);
        InputStream is = attendanceDataTempVO.getIs();
        String name = attendanceDataTempVO.getFileName();
        ParamException.notNull(is, "模板生成失败");

        // 编码文件名，防止乱码
        String filenames = new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE,"application/vnd.ms-excel")
                .body(new InputStreamResource(is));
    }

    @Override
    @GetMapping("/workHoursInfoById/{attendanceDataTempId}")
    public Result<AttendanceDataTempVO> workHoursInfoById(@PathVariable String attendanceDataTempId) {
        TokenUser tokenUser = UserContext.getUser();
        return Result.success(
                attendanceDataTempService.workHoursInfoById(attendanceDataTempId,tokenUser)
        );
    }

    @Override
    @GetMapping("/getWorkHoursInfoById/{attendanceDataTempId}")
    public Result<AttendanceDataTempVO> getWorkHoursInfoById(@PathVariable String attendanceDataTempId) {
        TokenUser tokenUser = UserContext.getUser();
        return Result.success(
                attendanceDataTempService.getWorkHoursInfoById(attendanceDataTempId,tokenUser)
        );
    }

    @Override
    @GetMapping("/attendanceDataInfo")
    public Result<Page<AttendanceDataTempListVO>> attendanceDataInfo(@Valid AttendanceDataTempQuery attendanceDataTempQuery) {
        TokenUser tokenUser = UserContext.getUser();
        return Result.success(
                attendanceDataTempService.attendanceDataInfo(attendanceDataTempQuery,tokenUser)
        );
    }

    @Override
    @GetMapping("/getAttendanceDataInfo")
    public Result<Page<AttendanceDataTempListVO>> getAttendanceDataInfo(AttendanceDataTempQuery attendanceDataTempQuery) {
        TokenUser tokenUser = UserContext.getUser();
        return Result.success(
                attendanceDataTempService.getAttendanceDataInfo(attendanceDataTempQuery,tokenUser)
        );
    }

    @Override
    @GetMapping("/newCalculateSalary/{recordId}")
    public Result<Integer> newCalculateSalary(@PathVariable String recordId) {
        TokenUser tokenUser = UserContext.getUser();
        return Result.success(
                attendanceDataTempService.newCalculateSalary(recordId,tokenUser)
        );
    }

    @Override
    @GetMapping("/calculateSalary/{recordId}")
    public Result<Integer> calculateSalary(@PathVariable String recordId) {
        TokenUser tokenUser = UserContext.getUser();
        return Result.success(
                attendanceDataTempService.calculateSalary(recordId,tokenUser)
        );
    }

    @Override
    @PostMapping("/handleError")
    public Result<Integer> handleError(AttendanceDataTempQuery attendanceDataTempQuery) {
        TokenUser tokenUser = UserContext.getUser();
        return Result.success(
                attendanceDataTempService.handleError(attendanceDataTempQuery,tokenUser)
        );
    }

    @Override
    @GetMapping("/getAttendanceDataTempAllAndError")
    public Result<AttendanceDataAllAndErrorVO> getAttendanceDataTempAllAndError(AttendanceDataTempQuery attendanceDataTempQuery) {
        TokenUser tokenUser = UserContext.getUser();
        return Result.success(
                attendanceDataTempService.getAttendanceDataTempAllAndError(attendanceDataTempQuery,tokenUser)
        );
    }

    @Override
    @PostMapping(value = "/newImportFile",headers = "content-type=multipart/form-data")
    public Result<AttendanceDataAllAndErrorVO> newImportFile(@RequestParam("file")MultipartFile file,
                                                             AttendanceDataTempQuery attendanceDataTempQuery) {
        TokenUser tokenUser = UserContext.getUser();
        if(file == null || file.isEmpty()){
            throw new HrException("上传文件失败");
        }
        return Result.success(
                attendanceDataTempService.newImportFile(file, attendanceDataTempQuery,tokenUser)
        );
    }

    @Override
    @PostMapping(value = "/importFile",headers = "content-type=multipart/form-data")
    public Result<AttendanceDataAllAndErrorVO> importFile(@RequestParam("file") MultipartFile file,
                                                          AttendanceDataTempQuery attendanceDataTempQuery) {
        TokenUser tokenUser = UserContext.getUser();
        if(file == null || file.isEmpty()){
            throw new HrException("上传文件失败");
        }
        return Result.success(
                attendanceDataTempService.importFile(file, attendanceDataTempQuery,tokenUser)
        );

    }

    @Override
    @PostMapping
    public Result<AttendanceDataTempVO> save(@Valid @RequestBody AttendanceDataTempAddDTO attendanceDataTempAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增临时考勤数据权限校验

        return Result.success(
                attendanceDataTempService.save(attendanceDataTempAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody AttendanceDataTempUpdateDTO attendanceDataTempUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改临时考勤数据权限校验

        int count = attendanceDataTempService.update(attendanceDataTempUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }



    @Override
    @DeleteMapping(value = "/{attendanceDataTempId}")
    public Result<Integer> delete(@PathVariable String attendanceDataTempId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除临时考勤数据权限校验

        int count = attendanceDataTempService.deleteByIds(tokenUser, attendanceDataTempId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] attendanceDataTempIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除临时考勤数据权限校验

        int count = attendanceDataTempService.deleteByIds(tokenUser, attendanceDataTempIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{attendanceDataTempId}")
    public Result<AttendanceDataTempVO> findById(@PathVariable String attendanceDataTempId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看临时考勤数据权限校验

        return Result.success(
            attendanceDataTempService.selectById(attendanceDataTempId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<AttendanceDataTempListVO>> listAll(@Valid AttendanceDataTempQuery attendanceDataTempQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看临时考勤数据权限校验

        return Result.success(
            attendanceDataTempService.select(attendanceDataTempQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<AttendanceDataTempListVO>> page(@Valid AttendanceDataTempQuery attendanceDataTempQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
            attendanceDataTempService.selectPage(attendanceDataTempQuery, tokenUser.getSiteId())
        );
    }


}

